// pages/profile/friendInfo/index.ts
import tran from "../../utils/language";
import {
    contactFriend,
    contactBlacklist,
    deleteContactFriend,
    userTargetInfo,
    profilePhone,
    eqTestResult,
} from "../../utils/api.js";
Page({
    /**
     * 组件的初始数据
     */
    data: {
        _t: tran._t("homeFriendInfo"),
        navBarHeight: getApp().globalData.navBarHeight,
        _tBase: tran._t("base"),
        indicatorDots: false,
        vertical: false,
        autoplay: false,
        interval: 2000,
        duration: 500,
        showEventPopup: false,
        imgList: [
            {
                img: "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                selectFlag: true,
            },
        ],
        selectBtnList: [
            {
                selectFlag: true,
                text: "烹饪",
            },
        ],
        skillList: [
            {
                selectFlag: true,
                text: "数据分析",
                img: "/images/expert.png",
            },
        ],
        langList: [
            {
                selectFlag: true,
                text: "英语",
            },
        ],
        personalityData: [
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
        ],
        popupParams: {
            showPopup: false,
            showType: 0, // 0更新个人资料  1发送好友请求
        },
        skillPopupParams: {
            showPopup: false,
        },
        sendFlag: true,
        hasSendFlag: true,
        userInfo: {
            interests: [],
            skills: [],
            userId: "",
        },
        interestList: [],
        professionList: [],
        loginInfo: {
            interestIds: [],
            skills: [],
        },
        levelList: [
            {
                text: tran._t("homeFriendInfo")["basicText"],
                img: "/images/mango1.png",
            },
            {
                text: tran._t("homeFriendInfo")["intermediateText"],
                img: "/images/mango2.png",
            },
            {
                text: tran._t("homeFriendInfo")["advancedText"],
                img: "/images/mango3.png",
            },
            {
                text: tran._t("homeFriendInfo")["expertText"],
                img: "/images/mango4.png",
            },
        ],
        confirmPopup: {
            showPopup: false,
            topTitle: tran._t("base").topTitleTip,
            midText: tran._t("base").blockNameTip,
            confirmText: tran._t("base").confirmText,
            closeText: tran._t("base").closeBtnText,
        },
        professionText: "",
        isSendFlag: false,
        homeFriendInfo: {
            userId: "",
            homeFriendInfoFlag: "",
            friendStatus: 0,
            jumpType: "",
            requestPlayIds: "",
            requestHelpIds: "",
            requestTalkIds: "",
            avatarurl: "",
            nickname: "",
            personalityAvatar: "",
            friendSourceInfo: {
                friendStatus: 1,
            },
            userInfo: {
                userId: "",
                homeFriendInfoFlag: "",
                friendStatus: 0,
                jumpType: "",
                requestPlayIds: "",
                requestHelpIds: "",
                requestTalkIds: "",
                avatarurl: "",
                nickname: "",
                personalityAvatar: "",
                friendSourceInfo: {
                    friendStatus: 1,
                },
            },
            loginInfo: {},
            skillText: "",
            interestText: "",
            eqList: [
                {
                    w: 1,
                },
            ],
        },
        isLoginFlag: false,
    },
    onLoad() {},
    onShow() {
        // getApp().getTotalUnreadCount();
        console.log("====================================");
        console.log("show");
        console.log(getApp().globalData.totalUnread);

        console.log("====================================");
        getApp().updateTabBar(getApp().globalData.totalUnread);
        if (typeof this.getTabBar === "function" && this.getTabBar()) {
            this.getTabBar().setData({
                activeKey: "curriculumVitae",
            });
        }
        this.handleLoginData();
    },
    /**
     * 登录
     */
    async getLogin() {
        await getApp().getLogin();
        setTimeout(() => {
            this.handleLoginData();
        }, 2000);
    },
    /**
     * 处理登录数据
     */
    handleLoginData() {
        const loginInfo = wx.getStorageSync("loginInfo");
        let userInfo = wx.getStorageSync("userInfo");
        const interestList = wx.getStorageSync("interestList");
        const allProfessionList = wx.getStorageSync("professionList");
        let skillList: any = [];
        let interestTextList: any = [];
        let professionList: any = [];
        let {homeFriendInfo,isLoginFlag} = this.data
        if (userInfo && Object.keys(userInfo).length > 0) {
            userInfo.skills &&
                userInfo.skills.map((item: any) => {
                    skillList.push(item.tagName);
                });
            professionList =
                allProfessionList && allProfessionList.length > 0
                    ? allProfessionList.filter(
                          (item1: any) =>
                              item1.tagTypeId == userInfo.professionId
                      )
                    : [];
            console.log(professionList);

            userInfo.interestIds &&
                userInfo.interestIds.map((item: any) => {
                    const list =
                        interestList && interestList.length > 0
                            ? interestList.filter(
                                  (item1: any) => item1.tagTypeId == item
                              )
                            : [];
                    if (list.length > 0) {
                        interestTextList.push(list[0]);
                    }
                });
        } else {
            userInfo = {}
            homeFriendInfo = {
              userId: '',
              homeFriendInfoFlag: '',
              friendStatus: 0,
              jumpType: '',
              requestPlayIds: '',
              requestHelpIds: '',
              requestTalkIds: '',
              avatarurl: '',
              nickname: '',
              personalityAvatar: '',
              friendSourceInfo: {
                friendStatus: 1
              },
              userInfo: {
                userId: '',
                homeFriendInfoFlag: '',
                friendStatus: 0,
                jumpType: '',
                requestPlayIds: '',
                requestHelpIds: '',
                requestTalkIds: '',
                avatarurl: '',
                nickname: '',
                personalityAvatar: '',
                friendSourceInfo: {
                  friendStatus: 1
                },
              },
              loginInfo: {},
              skillText: '',
              interestText: '',
              eqList: [
                {
                  w:1
                }
              ]
            },
            isLoginFlag = false
          }
        this.setData(
            {
                userInfo,
                homeFriendInfo: userInfo,
                interestText: interestTextList,
                loginInfo,
                professionText:
                    professionList.length > 0 ? professionList[0].tagName : "",
                isLoginFlag: loginInfo && Object.keys(loginInfo).length > 0,
            },
            () => {
                if (userInfo && Object.keys(userInfo).length > 0) {
                    userInfo.avatarurl = userInfo.avatarurl || userInfo.avatar;
                    userInfo.nickname = userInfo.nickname || userInfo.pushName;
                    this.handleUserInfo(userInfo);
                }
            }
        );
    },
    goStatisticsData() {
        wx.navigateTo({
            url: `/pages/profile/participationStatistics/index`,
        });
    },
    toEdit() {
        getApp().globalData.profileFrom = "edit";
        wx.navigateTo({
            url: "/pages/profile/create-account/index?type=edit",
        });
    },

    /**
     * 获取eq列表
     */
    getEqList() {
        const params = {};
        eqTestResult(params).then((res) => {
            if (res && Object.keys(res).length > 0) {
                if (res.scoreAssessments) {
                    const timeText =
                        res.createTime && res.createTime != "0"
                            ? dayjs(res.createTime).format("YYYY/MM/DD")
                            : "";
                    let list: any = [
                        {
                            ...res,
                            timeText,
                        },
                    ];
                    this.setData({
                        eqList: list || [],
                    });
                } else {
                    this.setData({
                        eqList: [],
                    });
                }
            }
        });
    },
    confirmFn() {
        const { userInfo } = this.data;
        // 调用 IM 的 API 将用户添加到黑名单
        wx.conn.addUsersToBlocklist({
            //可以添加单个用户 ID 或批量添加多个用户 ID 组成的数组。
            name: [userInfo.userId],
        });
        this.onCloseEventPopup();
        this.closeFn();
        setTimeout(() => {
            this.joinBlack();
        }, 300);
    },
    closeFn() {
        const { confirmPopup } = this.data;
        confirmPopup.showPopup = false;
        this.setData({
            confirmPopup,
        });
    },
    /**
     * 点击解锁个人资料
     */
    openUnlockInfo() {
        this.handleProfilePhone(true);
    },
    // 取消解锁按钮
    closeUnlockInfo() {
        this.handleProfilePhone(false);
    },
    // 解锁/取消解锁个人资料接口调用
    handleProfilePhone(unlock: any) {
        console.log(unlock);
        const { userInfo } = this.data;
        const params = {
            targetUserId: userInfo.userId,
            unlock: unlock, // true解锁  false取消解锁
        };
        profilePhone(params).then((res) => {
            wx.showToast({
                title: "操作成功",
            });
            this.closeFriend();
            this.setData({ showEventPopup: false });
        });
    },
    tapDot() {
        this.setData({
            showEventPopup: true,
        });
    },
    /**
     * 加入黑名单
     */
    joinBlackName() {
        const { confirmPopup } = this.data;
        confirmPopup.showPopup = true;
        this.setData({
            confirmPopup,
        });
    },
    /**
     * 加入黑名单（我们这边的接口，得先调用im的加入黑名单接口后，再调用此接口）
     */
    joinBlack() {
        const { userInfo } = this.data;
        const params = {
            tagetUserId: userInfo.userId,
            flag: true, // true加入黑名单 false移除黑名单
        };
        contactBlacklist(params).then((res: any) => {
            wx.showToast({
                title: "操作成功",
            });
            this.closeFriend();
        });
    },
    /**
     * 删除好友
     */
    deleteFriend() {
        const { userInfo } = this.data;
        const that = this;
        this.onClosePopup();
        wx.showModal({
            title: "提示",
            content: "确定要删除该用户？",
            success(res) {
                if (res.confirm) {
                    // 调用 IM 的 API 删除好友
                    wx.conn.deleteContact(userInfo.userId);
                    setTimeout(() => {
                        that.deleteFriendInt(userInfo.userId);
                    }, 300);
                } else if (res.cancel) {
                    console.log("用户点击取消");
                }
            },
        });
    },
    /**
     * 删除好友（先调用IM删除好友接口，再调此接口）
     */
    deleteFriendInt(targetUserId: string) {
        const params = {
            targetUserId: targetUserId,
        };
        deleteContactFriend(params).then((res: any) => {
            // this.getList()
        });
    },
    onCloseEventPopup() {
        // const customPopup = this.selectComponent('#event-popup');
        // customPopup && customPopup.hidePopup()
        this.setData({
            showEventPopup: false,
        });
    },
    getFriendAddMsg() {
        wx.conn.addEventHandler("contactEvent", {
            // 当前用户收到好友请求。用户 B 向用户 A 发送好友请求，用户 A 收到该事件。
            onContactInvited: function (msg: any) {
                console.log(msg, 1111);
            },
            // 当前用户被其他用户从联系人列表上移除。用户 B 将用户 A 从联系人列表上删除，用户 A 收到该事件。
            onContactDeleted: function (msg: any) {
                console.log(msg, 2222);
            },
            // 当前用户新增了联系人。用户 B 向用户 A 发送好友请求，用户 A 同意该请求，用户 A 收到该事件，而用户 B 收到 `onContactAgreed` 事件。
            onContactAdded: function (msg: any) {
                console.log(msg, 333);
            },
            // 当前用户发送的好友请求被拒绝。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，拒绝加好友，则用户 A 收到该事件。
            onContactRefuse: function (msg: any) {
                console.log(msg, 444);
            },
            // 当前用户发送的好友请求经过了对方同意。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，同意加好友，则用户 A 收到该事件。
            onContactAgreed: function (msg: any) {
                console.log(msg, 555);
            },
        });
        wx.conn.getRoster({
            success: function (roster: any) {
                console.log("好友列表:", roster);
                // 处理好友列表，筛选出待添加的好友请求
            },
            error: function (e: any) {
                console.error("获取好友列表失败:", e);
            },
        });
    },

    /**
     * 获取IM是否登录
     */
    async getImData() {
        const { userInfo } = this.data;
        const that = this;
        let wxIm = wx.conn;
        // 判断是否IM连接成功
        if (wxIm) {
            wx.conn.addContact(userInfo.userId, "添加好友");
            // 此处表示已查到im,就停止
            return;
        } else {
            // 如果没有wx.im，说明im还没连接成功，就再次调用getImData方法继续查
            setTimeout(() => {
                that.getImData();
            }, 500);
        }
    },
    closeFriend() {
        this.triggerEvent("onClose");
    },
    /**
     * 点击发送请求按钮
     */
    addFriendTap() {
        const { userInfo, popupParams, homeFriendInfo } = this.data;
        // 调用im接口后，在调用我们这边服务的接口
        // wx.conn.addContact(userInfo.userId, '添加好友')
        // 调用方法，然后调用添加好友
        this.getImData();
        let friendSource = "NONE";
        let friendSourceTagTypeId = "";
        if (homeFriendInfo.jumpType == "1") {
            // 找搭子
            friendSource = "INTEREST";
            friendSourceTagTypeId = homeFriendInfo.requestPlayIds || "";
        } else if (homeFriendInfo.jumpType == "2") {
            // 找师傅
            friendSource = "SKILL";
            friendSourceTagTypeId = homeFriendInfo.requestHelpIds || "";
        } else if (homeFriendInfo.jumpType == "3") {
            // 找朋友
            friendSource = "TOPIC ";
            friendSourceTagTypeId = homeFriendInfo.requestTalkIds || "";
        } else {
            // 普通进来的
            friendSource = "NONE";
        }
        const params = {
            tagetUserId: userInfo.userId, // 目标用户ID
            friendSource: friendSource, // 添加好友时的来源 NONE：无, INTEREST：兴趣, SKILL：技能, TOPIC：主题
            optionType: "ADD", // 操作类型  ADD：添加, AGREED：同意, REFUSE：拒绝
            friendSourceTagTypeId: friendSourceTagTypeId, // 添加好友时好友来源关联的标签类型ID
        };
        contactFriend(params).then((res: any) => {
            console.log(res);
        });
        homeFriendInfo.friendSourceInfo.friendStatus = 2;
        popupParams.showPopup = false;
        this.setData({
            popupParams,
            isSendFlag: true,
            homeFriendInfo,
        });
    },
    goChat(e: any) {
        const { homeFriendInfo } = this.data;
        wx.navigateTo({
            url: `/pages/profile/userChat/index?info=${JSON.stringify(
                homeFriendInfo
            )}`,
        });
    },
    /**
     * 获取登录的用户的详情
     */
    getLoginInfo() {
        const loginInfo = wx.getStorageSync("userInfo");
        this.setData({
            loginInfo,
        });
    },
    /**
     * 处理用户的兴趣与技能
     */
    getprofessionAndInterest() {
        const { userInfo, loginInfo } = this.data;
        // 获取用户的兴趣和技能
        const { interests, skills } = userInfo;
        interests &&
            interests.length > 0 &&
            interests.map((item: any) => {
                // const list = logininterests.filter((item1: any) => item1 == item.tagTypeId)
                // if (list.length > 0) {
                item.selectFlag = true;
                // }
            });
        skills.length > 0 &&
            skills.map((item: any) => {
                item.img = "/images/expert.png";
                // const list = loginSkills.filter((item1: any) => item1.tagTypeId == item.tagTypeId)
                // if (list.length > 0) {
                item.selectFlag = true;
                // }
                if (item.skillProficiency == "BASIC") {
                    // 基础
                    item.img = "/images/mango1.png";
                } else if (item.skillProficiency == "INTERMEDIATE") {
                    item.img = "/images/mango2.png";
                } else if (item.skillProficiency == "ADVANCED") {
                    item.img = "/images/mango3.png";
                } else {
                    // 专家
                    item.img = "/images/mango4.png";
                }
            });
        this.setData({
            interestList: interests,
            professionList: skills,
        });
    },
    handleUserInfo(info: any) {
        let imgList: any = [];
        const { photos, languages } = info;
        photos &&
            photos.length > 0 &&
            photos.map((item: any, index: Number) => {
                const obj = {
                    img: item,
                    selectFlag: index == 0 ? true : false,
                };
                imgList.push(obj);
            });
        let list: any = [];
        languages.length > 0 &&
            languages.map((item: any) => {
                let obj = {
                    value: item,
                    text: "",
                };
                if (item == "zh_CN") {
                    obj.text = "普通话";
                } else if (item == "en_US") {
                    obj.text = "英语";
                }
                list.push(obj);
            });
        this.setData(
            {
                userInfo: info,
                imgList,
                langList: list,
            },
            () => {
                this.getLoginInfo();
                this.getprofessionAndInterest();
            }
        );
    },
    addFriend() {
        let { popupParams } = this.data;
        popupParams.showPopup = true;
        popupParams.showType = 1; // 发送好友请求
        this.setData({
            popupParams,
        });
    },
    openLevel() {
        const { skillPopupParams } = this.data;
        skillPopupParams.showPopup = true;
        this.setData({
            skillPopupParams,
        });
    },
    closeLevelPopup() {
        const { skillPopupParams } = this.data;
        skillPopupParams.showPopup = false;
        this.setData({
            skillPopupParams,
        });
    },
    closePopup() {
        this.setData({ popupParams: { showPopup: false, showType: 1 } });
    },
    onClosePopup() {
        const customPopup = this.selectComponent("#custom-popup");
        customPopup && customPopup.hidePopup();
    },
    swiperChange(e: any) {
        const currentIndex = e.detail.current;
        const { imgList } = this.data;
        imgList.length > 0 &&
            imgList.map((item, index) => {
                if (index === currentIndex) {
                    item.selectFlag = true;
                } else {
                    item.selectFlag = false;
                }
            });
        this.setData({
            imgList,
        });
    },
    sendChange(e: any) {
        this.setData({
            sendFlag: e.detail,
        });
    },
    changeLangSelect(e: any) {
        const { info } = e.currentTarget.dataset;
        const { langList } = this.data;
        // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
        langList.map((item) => {
            if (item.text === info.text) {
                item.selectFlag = !item.selectFlag;
            }
        });
        this.setData({
            langList: langList,
        });
    },
    changeSkillSelect(e: any) {
        const { info } = e.currentTarget.dataset;
        const { skillList } = this.data;
        // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
        skillList.map((item) => {
            if (item.text === info.text) {
                item.selectFlag = !item.selectFlag;
            }
        });
        this.setData({
            skillList: skillList,
        });
    },
    changeSelect(e: any) {
        const { info } = e.currentTarget.dataset;
        const { selectBtnList } = this.data;
        // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
        selectBtnList.map((item) => {
            if (item.text === info.text) {
                item.selectFlag = !item.selectFlag;
            }
        });
        this.setData({
            selectBtnList: selectBtnList,
        });
    },
    changeIndicatorDots() {
        this.setData({
            indicatorDots: !this.data.indicatorDots,
        });
    },

    changeAutoplay() {
        this.setData({
            autoplay: !this.data.autoplay,
        });
    },

    intervalChange(e: any) {
        this.setData({
            interval: e.detail.value,
        });
    },

    durationChange(e: any) {
        this.setData({
            duration: e.detail.value,
        });
    },
});
